import { MenuResponse, MenuResponseTree } from "@/api/menu/menu";

// 数组去重
export function arrayDeduplication(arr: Array<MenuResponse>): MenuResponse[] {
  const notReplaceArr: MenuResponse[] = Object.values(
    arr.reduce((acc, obj) => {
      acc[obj.menuId] = obj;
      return acc;
    }, {} as any)
  );
  return notReplaceArr;
}
// 一维数组转换为多维数组
export function convertToNestedArray(
  arr: MenuResponse[],
  parentUuid = null
): MenuResponseTree[] {
  const result = [];
  for (const item of arr) {
    if (item.parentId === parentUuid) {
      const children = convertToNestedArray(arr, item.menuId);
      if (children.length > 0) {
        item.children = children;
      }
      result.push(item);
    }
  }
  return result;
}

export function getRoute(arr: any) {
  return arr.map(item => {
    const routeItem: RouteConfigsTable = {
      name: item.name,
      path: item.path,
      component: item.template,
      meta: {
        title: item.name,
        icon: item.icon,
        showLink: !item.hidden
      }
    };
    !item.template && delete routeItem.component;
    if (item.children) {
      routeItem.children = getRoute(item.children) as any;
    }
    return routeItem;
  });
}

export function getFinallyRoutes(arr: Array<any>) {
  const notReplaceArr = arrayDeduplication(arr).sort((a, b) => b.sort - a.sort);
  const converArr = convertToNestedArray(notReplaceArr);
  return getRoute(converArr);
}
